(function() {
    'use strict';
    
    // 获取存储的API令牌
    function getApiToken() {
        const authData = localStorage.getItem('telchinaAuth') || sessionStorage.getItem('telchinaAuth');
        
        if (!authData) {
            return null;
        }
        
        try {
            const loginData = JSON.parse(authData);
            return loginData.apiToken || null;
        } catch (e) {
            return null;
        }
    }
    
    // 创建带认证头的fetch请求
    function authenticatedFetch(url, options = {}) {
        const token = getApiToken();
        
        // 设置默认headers
        const defaultHeaders = {
            'Content-Type': 'application/json'
        };
        
        // 如果有token，添加认证头
        if (token) {
            defaultHeaders['x-Authentication-Token'] = token;
        }
        
        // 合并用户提供的headers
        const headers = {
            ...defaultHeaders,
            ...(options.headers || {})
        };
        
        // 合并选项
        const fetchOptions = {
            ...options,
            headers
        };
        
        return fetch(url, fetchOptions)
            .then(response => {
                // 检查响应状态
                if (response.status === 401) {
                    // 尝试解析响应体来检查具体错误
                    return response.json().then(data => {
                        if (data.type === 'error' && data.error === '未提供认证令牌') {
                            // 清除登录状态并重定向到登录页面
                            localStorage.removeItem('telchinaAuth');
                            sessionStorage.removeItem('telchinaAuth');
                            window.location.href = '/login.html?redirect=' + encodeURIComponent(window.location.pathname);
                            throw new Error('未提供认证令牌');
                        } else {
                            // 其他认证错误，返回原始响应
                            throw new Error(data.error || '认证失败');
                        }
                    }).catch(parseError => {
                        // 如果无法解析响应体，按原来的逻辑处理
                        localStorage.removeItem('telchinaAuth');
                        sessionStorage.removeItem('telchinaAuth');
                        window.location.href = '/login.html?redirect=' + encodeURIComponent(window.location.pathname);
                        throw new Error('认证失败');
                    });
                }
                return response;
            })
            .catch(error => {
                console.error('API请求失败:', error);
                throw error;
            });
    }
    
    // 便捷的API方法
    const apiClient = {
        get: (url, options = {}) => {
            return authenticatedFetch(url, {
                ...options,
                method: 'GET'
            });
        },
        
        post: (url, data, options = {}) => {
            return authenticatedFetch(url, {
                ...options,
                method: 'POST',
                body: JSON.stringify(data)
            });
        },
        
        put: (url, data, options = {}) => {
            return authenticatedFetch(url, {
                ...options,
                method: 'PUT',
                body: JSON.stringify(data)
            });
        },
        
        delete: (url, options = {}) => {
            return authenticatedFetch(url, {
                ...options,
                method: 'DELETE'
            });
        }
    };
    
    // 将API客户端暴露到全局
    window.apiClient = apiClient;
    window.authenticatedFetch = authenticatedFetch;
})();